import json
import threading

from djmockserver.mock.loader import mockloader
from djmockserver.mock.serializer import MockItem
from djmockserver.mock.jsoncompare import JsonCompare

class MockItemMatcher:
    _instance_lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        if not hasattr(MockItemMatcher, "_instance"):
            with MockItemMatcher._instance_lock:
                if not hasattr(MockItemMatcher, "_instance"):
                    MockItemMatcher._instance = object.__new__(cls)
        return MockItemMatcher._instance

    def match(self, request) -> MockItem:
        mockitem_list = mockloader.data.get(request.uri)

        if mockitem_list:
            if len(mockitem_list) == 1:
                # uri只配置一个响应时只需要匹配uri即可
                return mockitem_list[0]

            for item in mockitem_list:
                # item.req为有序字典，需要转为普通字典才能与request.req比较
                if JsonCompare().compare(request.req, json.loads(json.dumps(item.req)), ignore_order=True):
                    return item
        # 匹配失败,返回空mockitem
        return MockItem({})

mockitem_matcher = MockItemMatcher()